#include <iostream>
using namespace std;
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <cstring>
#include <string>
#define BUFFER_SIZE 16
int main()
{   
    int pipefd[2];
    //清空脏数据
    memset(pipefd,0,sizeof(pipefd));
    //创建管道
    pipe(pipefd);
    //创建子进程
    pid_t pid = fork();
    if(pid > 0)
    {   
        close(pipefd[0]);
        cout<<"l am parent process!"<<endl;
        // string res = "hello world!";
        // //父进程负责写数据
        // write(pipefd[1],res.c_str(),res.size());
        //回收子进程的资源
        wait(NULL);
    }
    else if(pid == 0)
    {   
        close(pipefd[1]);
        sleep(3);
        cout<<"l am child process!"<<endl;

        //得到文件描述符的状态标记
        int flags =fcntl(pipefd[0],F_GETFL);
        cout<<"flags:"<<flags<<endl;

        //设置文件描述符为非阻塞
        fcntl(pipefd[0],F_SETFL,flags | O_NONBLOCK);

        //子进程负责读 -(read是一个阻塞函数：没有函数是阻塞的，只有文件描述符是阻塞的)
        char buffer[BUFFER_SIZE] = {0};
        read(pipefd[0],buffer,sizeof(buffer));

        printf("hello world\n");
        printf("buffer = %s\n",buffer);
    }
    else
    {
        
    }
    return 0;
}